package tt.dz.egobus.servicemanager.business.convert;

import org.springframework.core.convert.converter.Converter;
import tt.dz.egobus.servicemanager.business.key.BusinessCache;
import tt.dz.egobus.servicemanager.business.task.job.BusinessCacheGrabDynamicTask;
import tt.dz.egobus.servicemanager.business.task.job.QuartzDynamicTask;
import tt.dz.egobus.servicemanager.core.task.DynamicTask;
import tt.dz.egobus.servicemanager.core.task.DynamicTaskNamespace;
import tt.dz.egobus.vo.KV;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @author Anson
 * @date 17-8-9
 * @name 业务缓存转换成动态任务数据
 * @since 1.0.6
 */
public class DynamicTaskConvert<T extends QuartzDynamicTask> implements Converter<BusinessCache, DynamicTask> {

    /**
     * 当前定时任务执行器
     */
    public final Class<T> clazz;
    /**
     * 当前执行开始时间
     */
    public final Date startTime;

    public DynamicTaskConvert(Class<T> clazz, Date startTime) {
        this.clazz = clazz;
        this.startTime = startTime;
    }


    @Override
    public DynamicTask convert(BusinessCache source) {
        if (source == null) {
            return null;
        }
        DynamicTaskNamespaceConvert convert = new DynamicTaskNamespaceConvert();
        convert.setDynamicExecutorTask(clazz);
        DynamicTaskNamespace dynamicTaskNamespace = convert.convert(source);
        if (dynamicTaskNamespace == null) {
            return null;
        }
        List<KV<String, String>> jobDatas = new ArrayList<>();
        jobDatas.add(new KV<>(BusinessCacheGrabDynamicTask.BUSINESS_CACHE_JOB_KEY, source.getBusinessId()));
        DynamicTask task = new DynamicTask();
        task.setJobClassName(this.clazz.getName());
        task.setJobDatas(jobDatas);
        task.setJobGroupName(dynamicTaskNamespace.getJobGroupName());
        task.setJobName(dynamicTaskNamespace.getJobName());
        task.setTriggerGroupName(dynamicTaskNamespace.getTriggerGroupName());
        task.setTriggerName(dynamicTaskNamespace.getTriggerName());
        task.setStartTime(startTime);
        return task;
    }

}
